﻿using System;
using UnityEngine;

namespace Core
{
    /// <summary>
    /// 前缀 tgl_XXX Toggle
    /// </summary>
    public class UIToggle : UIWidget
    {
#pragma warning disable 0649
        [UIField("Label")]
        private readonly UILabel txt_desc;
#pragma warning restore 0649

        private UnityEngine.UI.Toggle toggle;

        public string text
        {
            get { return txt_desc != null ? txt_desc.text : string.Empty; }
            set { if (txt_desc != null) { txt_desc.text = value; } }
        }

        public bool interactable
        {
            get { return toggle.interactable; }
            set { toggle.interactable = value; }
        }

        public bool isOn
        {
            get { return toggle.isOn; }
            set { toggle.isOn = value; }
        }

        public bool Frozen { get; set; }

        public Action<bool> OnValueChanged;

        public override void Awake(GameObject go)
        {
            base.Awake(go);

            toggle = go.GetComponent<UnityEngine.UI.Toggle>();

            toggle.onValueChanged.AddListener(OnValueChangedHandler);
        }

        public override void Dispose()
        {
            if (IsDisposed) return;

            toggle.onValueChanged.RemoveListener(OnValueChangedHandler);
            toggle = null;

            base.Dispose();
        }

        private void OnValueChangedHandler(bool arg0)
        {
            if (Frozen) return;
            OnValueChanged?.Invoke(arg0);
        }
    }
}
